package com.me.test.util;

import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

@Slf4j
public class FileUtil {

    /**
     * @param fileUrl 资源地址
     * @Description: 网络资源转file, 用完以后必须删除该临时文件
     * @return: 返回值
     */
    public static File urlToFile(String fileUrl) {
        String path = System.getProperty("user.dir");
        File tmpFile = new File(path, "tmp");
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        return urlToFile(fileUrl, tmpFile);
    }

    /**
     * @param fileUrl 资源地址
     * @param tmpFile  临时文件
     * @Description: 网络资源转file, 用完以后必须删除该临时文件
     * @return: 返回值
     */
    public static File urlToFile(String fileUrl, File tmpFile) {
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/"));
        FileOutputStream downloadFile = null;
        InputStream openStream = null;
        File savedFile = null;
        try {
            savedFile = new File(tmpFile.getAbsolutePath() + fileName);
            URL url = new URL(fileUrl);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
            openStream = connection.getInputStream();
            int index;
            byte[] bytes = new byte[1024];
            downloadFile = new FileOutputStream(savedFile);
            while ((index = openStream.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (openStream != null) {
                    openStream.close();
                }
                if (downloadFile != null) {
                    downloadFile.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return savedFile;
    }

}
